# coding=utf-8
'''
Created on 2016年3月4日
'''

import torndb
from pymongo.mongo_client import MongoClient
from util_base.server_context import ServerContext
from util_base.db_utils import MysqlConnPool, PooledConnection
from util_base.exception import ParamException
from util_base import common_utils
import redis
import os


def get_service_info():
    '''
    解析主机上应该运行的服务
    '''
    
    # 解析ufo service name
    _cfg = {}
    qingcloud_data_file = '/etc/qingcloud/userdata/userdata.string'
    if os.path.exists(qingcloud_data_file):
        with open(qingcloud_data_file) as f:
            for line in f:
                line = line.strip()
                if line:
                    k, v = line.split('=')
                    _cfg[k] = v
                    
    hostname = common_utils.get_local_hostname()                
    
    env = _cfg.get('env') or hostname.split('-')[-2]
    service = _cfg.get('service') or hostname.split('-')[-1]
    
    
    info_list = hostname.split('-')
    if info_list[-2].lower() in ('dev','ft','prod','pre','yuanyong'):
        env = _cfg.get('env') or hostname.split('-')[-2]
        service = _cfg.get('service') or hostname.split('-')[-1]
    elif info_list[-3].lower() in ('dev','ft','prod','pre','yuanyong'):
        env = _cfg.get('env') or hostname.split('-')[-3]
        service = _cfg.get('service') or hostname.split('-')[-2]
    
    return env.upper(), service


    
def set_mysql_pool(server_config):
    '''
    '''
    
    app = ServerContext.application
    MysqlConnPool.lock(clear=True)
    
    db_names = app.db_names
    for db_name in db_names:
        for mode in ('read', 'write'):
            conn_name = db_name + '_' + mode
            MysqlConnPool.init_pool(conn_name, server_config("DATABASE")[db_name][mode])
            
    MysqlConnPool.unlock()
    
    
def get_db_conns(server_config, use_pool=False):
    '''
    初始化数据库连接
    :param use_pool: 是否使用连接池模式
    '''
    
    db_conns = {}
    
    app = ServerContext.application
    
    # alive mysql数据库
    db_names = app.db_names
    for db_name in db_names:
        for mode in ('read', 'write'):
            conn_name = db_name + '_' + mode
            if use_pool:
                db_conns[conn_name] = PooledConnection(server_config('BASIC')['EXECUTOR_COUNT'] + 1, conn_name, server_config("DATABASE")[db_name][mode])
            else:
                db_conns[conn_name] = torndb.Connection(**server_config("DATABASE")[db_name][mode])
    
    # mongo
    mongo_db_names = app.mongo_db_names
    for db_name in mongo_db_names:
        
        for mode in ('read', 'write'):
            
            # 如果没有特殊配置 读取默认的
            mongo_db_name = db_name
            if not server_config("DATABASE").get(db_name, {}):
                mongo_db_name = 'mongo'
                
            conn_name = mongo_db_name + '_' + mode
            if db_conns.get(conn_name, None):
                continue
            
            hosts = [str(host) + ':' + str(server_config("DATABASE")[mongo_db_name][mode]['port']) for host in server_config("DATABASE")[mongo_db_name][mode].get('hosts', [])]
            if hosts:
                hosts_config = ','.join(hosts)
                db_conns[conn_name] = MongoClient('mongodb://%s:%s@%s/admin?replicaSet=%s' % (server_config("DATABASE")[mongo_db_name][mode]['username'], server_config("DATABASE")[mongo_db_name][mode]['password'], hosts_config, server_config("DATABASE")[mongo_db_name][mode]['replSet']))
            else:
                db_conns[conn_name] = MongoClient('mongodb://%s:%s@%s:%s/admin' % (server_config("DATABASE")[mongo_db_name][mode]['username'], server_config("DATABASE")[mongo_db_name][mode]['password'], server_config("DATABASE")[mongo_db_name][mode]['host'], server_config("DATABASE")[mongo_db_name][mode]['port']))

    # redis dbs
    # 由于redis客户端没有实现切换库的方法, 所以根据配置中指定的redis库分别建立连接
    for i in server_config("DATABASE")['REDIS_DBS']:
        db_conns['redis_read_%d' % i] = redis.StrictRedis(db=i, **server_config("DATABASE")['redis']['read'])
        db_conns['redis_write_%d' % i] = redis.StrictRedis(db=i, **server_config("DATABASE")['redis']['write'])
    
    return db_conns


def mysql_url(**kwargs):
    '''
    '''
    
    return 'mysql://%s:%s@%s:%s/%s'% (
                                      kwargs.get('user', 'root'),
                                      kwargs.get('password', ''),
                                      kwargs.get('host', 'localhost'),
                                      kwargs.get('port', '3306'),
                                      kwargs.get('database')
                                      )

def assert_item_in_param(params, items):
    for item in items:
        if item not in params:
            raise ParamException(item)
        

